import React, { useEffect, useRef, useState } from 'react';
import Chart from 'chart.js/auto';
import * as echarts from 'echarts';

interface ChartsData {
  barChart: {
    title: string;
    labels: string[];
    values: number[];
    color: string;
  };
  pieChart: {
    title: string;
    labels: string[];
    values: number[];
    colors: string[];
  };
  lineChart: {
    title: string;
    labels: string[];
    values: number[];
    color: string;
  };
  doughnutChart: {
    title: string;
    labels: string[];
    values: number[];
    colors: string[];
  };
}

export const ChartPanel: React.FC = () => {
  const barChartRef = useRef<HTMLCanvasElement>(null);
  const pieChartRef = useRef<HTMLCanvasElement>(null);
  const cpuChartRef = useRef<HTMLDivElement>(null);
  const otherChartRef = useRef<HTMLCanvasElement>(null);
  
  const [chartsData, setChartsData] = useState<ChartsData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  
  // 存储图表实例的引用，便于清理
  const chartInstances = useRef<{
    barChart: Chart | null;
    pieChart: Chart | null;
    cpuChart: echarts.ECharts | null;
    otherChart: Chart | null;
  }>({
    barChart: null,
    pieChart: null,
    cpuChart: null,
    otherChart: null
  });

  // 从JSON文件加载图表数据
  useEffect(() => {
    const fetchChartsData = async () => {
      try {
        const response = await fetch('/data/charts/charts-data.json');
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setChartsData(data);
        setLoading(false);
      } catch (err) {
        console.error('加载图表数据失败:', err);
        setError('加载图表数据失败，请检查网络连接');
        setLoading(false);
      }
    };

    fetchChartsData();
    
    // 设置定期刷新数据的间隔（每60秒刷新一次）
    const intervalId = setInterval(fetchChartsData, 60000);
    
    // 清理函数
    return () => {
      clearInterval(intervalId);
      // 清理Chart.js图表
      if (chartInstances.current.barChart) chartInstances.current.barChart.destroy();
      if (chartInstances.current.pieChart) chartInstances.current.pieChart.destroy();
      if (chartInstances.current.otherChart) chartInstances.current.otherChart.destroy();
      
      // 清理ECharts图表
      if (chartInstances.current.cpuChart) chartInstances.current.cpuChart.dispose();
    };
  }, []);

  // 创建ECharts的CPU使用率图表
  const createCpuChart = () => {
    if (!cpuChartRef.current || !chartsData) return;
    
    // 如果已经有图表实例，先销毁
    if (chartInstances.current.cpuChart) {
      chartInstances.current.cpuChart.dispose();
    }
    
    // 初始化ECharts实例
    const cpuChart = echarts.init(cpuChartRef.current);
    chartInstances.current.cpuChart = cpuChart;
    
    // 配置图表选项
    const option = {
      title: {
        text: chartsData.lineChart.title,
        textStyle: {
          color: '#fff'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}%'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartsData.lineChart.labels,
        axisLabel: {
          color: '#fff'
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%',
          color: '#fff'
        }
      },
      series: [
        {
          name: 'CPU使用率',
          type: 'line',
          data: chartsData.lineChart.values,
          itemStyle: {
            color: chartsData.lineChart.color
          },
          lineStyle: {
            width: 3,
            color: chartsData.lineChart.color
          },
          symbol: 'circle',
          symbolSize: 8,
          animation: false
        }
      ]
    };
    
    // 使用配置项设置图表
    cpuChart.setOption(option);
  };

  // 用于创建或更新图表的函数
  const updateCharts = () => {
    if (!chartsData) return;
    
    // 创建柱状图
    if (barChartRef.current) {
      const barCtx = barChartRef.current.getContext('2d');
      if (barCtx) {
        // 清除之前的图表
        if (chartInstances.current.barChart) {
          chartInstances.current.barChart.destroy();
        }
        
        // 创建新图表
        chartInstances.current.barChart = new Chart(barCtx, {
          type: 'bar',
          data: {
            labels: chartsData.barChart.labels,
            datasets: [
              {
                label: '流量 (KB/s)',
                data: chartsData.barChart.values,
                backgroundColor: chartsData.barChart.color,
              },
            ],
          },
          options: { 
            responsive: true, 
            maintainAspectRatio: false,
            animation: {
              duration: 0 // 禁用动画
            },
            plugins: {
              title: {
                display: true,
                text: chartsData.barChart.title
              }
            }
          },
        });
      }
    }

    // 创建饼图
    if (pieChartRef.current) {
      const pieCtx = pieChartRef.current.getContext('2d');
      if (pieCtx) {
        // 清除之前的图表
        if (chartInstances.current.pieChart) {
          chartInstances.current.pieChart.destroy();
        }
        
        // 创建新图表
        chartInstances.current.pieChart = new Chart(pieCtx, {
          type: 'pie',
          data: {
            labels: chartsData.pieChart.labels,
            datasets: [
              {
                data: chartsData.pieChart.values,
                backgroundColor: chartsData.pieChart.colors,
              },
            ],
          },
          options: { 
            responsive: true, 
            maintainAspectRatio: false,
            animation: {
              duration: 0 // 禁用动画
            },
            plugins: {
              title: {
                display: true,
                text: chartsData.pieChart.title
              }
            }
          },
        });
      }
    }

    // 创建CPU使用率图表（使用ECharts）
    createCpuChart();

    // 创建环形图
    if (otherChartRef.current) {
      const otherCtx = otherChartRef.current.getContext('2d');
      if (otherCtx) {
        // 清除之前的图表
        if (chartInstances.current.otherChart) {
          chartInstances.current.otherChart.destroy();
        }
        
        // 创建新图表
        chartInstances.current.otherChart = new Chart(otherCtx, {
          type: 'doughnut',
          data: {
            labels: chartsData.doughnutChart.labels,
            datasets: [
              {
                data: chartsData.doughnutChart.values,
                backgroundColor: chartsData.doughnutChart.colors,
              },
            ],
          },
          options: { 
            responsive: true, 
            maintainAspectRatio: false,
            animation: {
              duration: 0 // 禁用动画
            },
            plugins: {
              title: {
                display: true,
                text: chartsData.doughnutChart.title
              }
            }
          },
        });
      }
    }
  };

  // 当窗口大小改变时，调整ECharts图表大小
  useEffect(() => {
    const handleResize = () => {
      if (chartInstances.current.cpuChart) {
        chartInstances.current.cpuChart.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 当数据加载完成后渲染图表
  useEffect(() => {
    if (!loading && chartsData && !error) {
      updateCharts();
    }
  }, [loading, chartsData, error]);

  if (loading) {
    return (
      <div className="chart-panel loading-container">
        <div className="loading">加载中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="chart-panel error-container">
        <div className="error">{error}</div>
      </div>
    );
  }

  return (
    <div className="chart-panel">
      <h2>图表面板</h2>
      <div className="chart-row">
        <div className="chart-container">
          <canvas ref={barChartRef}></canvas>
        </div>
        <div className="chart-container">
          <canvas ref={pieChartRef}></canvas>
        </div>
      </div>
      <div className="chart-row">
        <div className="chart-container">
          <div ref={cpuChartRef} style={{ width: '100%', height: '100%' }}></div>
        </div>
        <div className="chart-container">
          <canvas ref={otherChartRef}></canvas>
        </div>
      </div>
    </div>
  );
}; 